# src\core\retMes.py
from fastapi import HTTPException
from src.models.sys_message import SysMessage
from src.core import str_utils as strU
from src.core.config import Config


class Success:
    def __init__(self, data=None, message=None, record_count=None, status_code=200):
        self.status_code = status_code
        self.status = 'success'
        self.record_count = record_count if record_count is not None else 0
        self.message = message if message is not None else 'Operation successful.'
        self.data = data if data is not None else {}

    def mes(self):
        return {
            'status_code': self.status_code,
            'status': self.status,
            'message': self.message,
            'record_count': self.record_count,
            'data': self.data
        }


class Error:
    def __init__(self, message=None, data=None, status_code=400):
        self.status_code = status_code
        self.status = 'error'
        self.message = message if message is not None else 'Operation error.'
        self.data = data if data is not None else {}

    def mes(self):
        return {
            'status_code': self.status_code,
            'status': self.status,
            'message': self.message,
            'data': self.data
        }


class Raise:
    def __init__(self, message=None, data=None, status_code=403):
        self.status_code = status_code
        self.status = 'error'
        self.message = message if message is not None else 'Operation error.'
        self.data = data if data is not None else {}

    def mes(self):
        raise HTTPException(status_code=self.status_code, detail=self.message)


# 在原文件末尾追加（render_msg 与 I18nMsg 放一起）
def render_msg(db, api_id, code, language=None, *args):
    """从 sys_message 取模板并填充 %s"""
    if strU.is_empty(language):
        language = Config.MESSAGE_DEFAULT_LANGUAGE
    row = db.query(SysMessage.message).filter(
        SysMessage.api_id == api_id,
        SysMessage.language == language,
        SysMessage.code == code,
        SysMessage.deletion_mark == 0
    ).first()
    if not row:
        return f"Unknown error {code}"
    tpl = row.message
    tpl = row.message
    need_cnt = tpl.count("%s")
    use_args = args[:need_cnt]
    retMessage=tpl % use_args if use_args else tpl
    retMessage = retMessage.replace("：%s", "")
    retMessage = retMessage.replace(":%s", "")
    retMessage=retMessage.replace("%s", "")
    return retMessage


class Msg:
    def __init__(self, db, api_id, code, language="zh", *args):
        self.msg = render_msg(db, api_id,code, language, *args)

    def mes(self):
        return self.msg
